﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Jamhee.Noctiluca.Common;
using Jamhee.Noctiluca.WebServer;
using System.Web;

namespace Jamhee.Noctiluca.LightWiki
{
    class WikiUtils
    {
        public enum DocType
        {
            WikiContent,
            PageInfo
        }

        public static string GetDocument(Uri url, IWebConfiguration webConfig, DocType docType)
        {
            string dirs = webConfig.GetWebsiteRootPath();
            StringBuilder sBuilder = new StringBuilder();
            string retPath = "";

            // Build all possible paths
            foreach (string dir in dirs.Split('|'))
            {
                sBuilder.Remove(0, sBuilder.Length);
                sBuilder.Append(dir);

                // Here, we want to redirect the URL
                //  (1) If the URL is not a file (e.g. http://localhost/abc/def), we redirect it to http://localhost/abc/def/content
                //  (2) If the URL is a file, we return the URL directly
                for (int i = 0; i < url.Segments.Length; i++)
                {
                    string decodedSegment = HttpUtility.UrlDecode(url.Segments[i]);

                    if (i == url.Segments.Length - 1 && url.Segments[i].IndexOf('.') < 0)
                    {
                        if (docType.Equals(DocType.PageInfo))
                        {
                            sBuilder.Append(decodedSegment + "\\" + WikiConstants.WIKI_DOC_INFO);
                        }
                        else
                        {
                            sBuilder.Append(decodedSegment + "\\" + WikiConstants.WIKI_DOC_CONTENT);
                        }
                    }
                    else
                    {
                        sBuilder.Append(decodedSegment);
                    }
                }


                if (retPath.Length > 0)
                {
                    retPath += "|";
                }

                retPath += AppUtil.GetAbsolutePath(sBuilder.ToString());
            }

            return retPath;
        }
    }
}
